package com.example.quartzdemo.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;

/**
 * @author jasondai
 * @date 2023/10/25 11:00
 */
@ControllerAdvice
public class GlobalExceptionAdvice {
    // ConstraintViolationException参数校验异常处理
    @ExceptionHandler(ConstraintViolationException.class)
    // 响应http状态码为400
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Object handleConstraintException (HttpServletRequest request, ConstraintViolationException e) {
        // 获取参数校验的异常信息，注解的message
        String errorMsg = e.getConstraintViolations().iterator().next().getMessage();
        HashMap<String,Object> result = new HashMap<>(2);
        result.put("code",400);
        result.put("errorMsg",errorMsg);
        return result;
    }
}
